<template>
  <view class="flex_header_main whov" @click.stop="initCountdown">
    <!-- <view class="flex_header_main whov" :style="{ paddingTop: statusBarHeight + 'px' }" @click.stop="initCountdown"> -->
    <view class="flex_header">
      <TitleTime :title="pointName || '智能寄存柜'" :deviceId="deviceId" v-if="deviceId" />
    </view>

    <view class="flex_main wrapper" style="width: 100%">
      <view style="width: 80%; margin-top: -30px">
        <view class="return_home flex_header" @click="onClick">
          <img src="@/assets/img/return.png" />
          <text class="time-range">返回首页</text>
        </view>
        <view class="baoguo_main_content">
          <view class="section_content">
            <text class="title flex_1">请输入信息开门</text>
            <view class="flex_1" style="flex: 2">
              <view class="form-item" @click="handleInputClick('phone')">
                <view class="label-wrapper">
                  <text class="label">手机号</text>
                </view>
                <uni-easyinput
                  class="input-box"
                  type="number"
                  placeholder="请输入手机号"
                  style="pointer-events: none"
                  v-model="phone"
                  maxlength="11"
                  :class="{ focused: activeInput === 'phone' }"
                  :disabled="true"
                  :clearable="false"
                  placeholder-style="color: #CBD5E0;"
                  tabindex="-1"
                />
              </view>

              <view class="form-item" @click="handleInputClick('password')">
                <view class="label-wrapper">
                  <text class="label">取包密码</text>
                </view>
                <uni-easyinput
                  class="input-box"
                  type="password"
                  placeholder="请输入取件密码"
                  v-model="password"
                  maxlength="4"
                  @click="handleInputClick('password')"
                  @focus="handleInputFocus('password')"
                  @keydown.native.stop.prevent="() => {}"
                  @input.native.stop.prevent="() => {}"
                  :class="{ focused: activeInput === 'password' }"
                  :disabled="true"
                  :clearable="false"
                  placeholder-style="color: #CBD5E0;"
                  tabindex="-1"
                />
              </view>
            </view>
            <view class="img_setp flex_left_right">
              <view class="flex_right img_row">
                <img src="@/assets/img/1.png" />
              </view>
              <view class="flex_right img_row wrapper img_row_right">
                <img src="@/assets/img/r.png" />
              </view>
              <view class="flex_right img_row">
                <img src="@/assets/img/2.png" />
              </view>
              <view class="flex_right img_row wrapper img_row_right">
                <img src="@/assets/img/r.png" />
              </view>
              <view class="flex_right img_row">
                <img src="@/assets/img/3.png" />
              </view>
            </view>
          </view>

          <view class="keyboard">
            <view class="keyboard-row">
              <text class="key wrapper" v-for="num in [1, 2, 3]" :key="num" @click="onKeyPress(num)">{{ num }}</text>
            </view>
            <view class="keyboard-row">
              <text class="key wrapper" v-for="num in [4, 5, 6]" :key="num" @click="onKeyPress(num)">{{ num }}</text>
            </view>
            <view class="keyboard-row">
              <text class="key wrapper" v-for="num in [7, 8, 9]" :key="num" @click="onKeyPress(num)">{{ num }}</text>
            </view>
            <view class="keyboard-row">
              <text class="key wrapper" @click="onKeyPress('*')">*</text>
              <text class="key wrapper" @click="onKeyPress(0)">0</text>
              <text class="key key-delete wrapper" @click="onDelete"> 删除 </text>
            </view>
            <view class="open-btn" @click="onOpen" :disabled="countdown === 0" :class="{ disabled: countdown === 0 }"> 开柜门（{{ countdown }}秒） </view>
          </view>
        </view>
      </view>
    </view>
    <view class="zzc_main wrapper" v-if="isShow">
      <view class="tip_dialog">
        <view class="title">{{ detail.pointName }}-{{ detail.doorNo }}</view>
        <view class="flex_left_right tip_text">
          <view class="flex_left">网点地址</view>
          <view class="flex_right" style="text-align: right">{{ detail.pointName }}</view>
        </view>
        <view class="flex_left_right tip_text">
          <view class="flex_left">寄存时间</view>
          <view class="flex_right" style="text-align: right">{{ detail.createTime }}</view>
        </view>
        <view class="flex_left_right">
          <view class="flex_right btn" style="margin-right: 30rpx" @click="openSubmit('2')">
            <view>还要存</view>
            <view class="btn_text">中途开门</view>
          </view>
          <view class="flex_right btn" style="margin-left: 30rpx" @click="openSubmit('3')">
            <view>不存了</view>
            <view class="btn_text">结束寄存</view>
          </view>
        </view>
        <view class="close" @click="isShow = false">
          <uni-icons type="close" size="30"></uni-icons>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref, onMounted, nextTick, onUnmounted, watch } from 'vue'
  import TitleTime from '@/components/TitleTime.vue'
  import { ordergetUserStoragePbEnd, orderPbEnd } from '@/api/comm'
  import { onLoad } from '@dcloudio/uni-app' // 使用uni-app的定时器API
  import { useFontSize } from '@/utils/fontSizeRootSetting'
  const { cleanup } = useFontSize()

  onUnmounted(cleanup)
  const phone = ref('')
  const isShow = ref(false)
  const password = ref('')
  const activeInput = ref('phone') // 默认激活手机号输入
  const status = ref('')
  const deviceId = ref('')
  const pointName = ref('')
  const detail = ref<any>({})

  // 倒计时相关变量
  const countdown = ref(180) // 倒计时总时长（秒）
  const countdownTimer = ref<number | null>(null)
  const endTime = ref<number>(0) // 使用结束时间戳替代开始时间戳，更直观

  // 初始化/重置倒计时
  const initCountdown = () => {
    // 清除旧定时器
    if (countdownTimer.value) {
      clearInterval(countdownTimer.value)
      countdownTimer.value = null
    }

    // 计算结束时间（当前时间 + 180秒）
    endTime.value = Date.now() + 180 * 1000
    countdown.value = 180

    // 使用uni-app的setInterval，兼容性更好
    countdownTimer.value = setInterval(() => {
      const now = Date.now()
      const remaining = Math.ceil((endTime.value - now) / 1000)

      // 确保剩余时间不为负
      if (remaining <= 0) {
        countdown.value = 0
        if (countdownTimer.value) {
          clearInterval(countdownTimer.value)
          countdownTimer.value = null
        }
        uni.navigateBack() // 跳回上一页
      } else {
        countdown.value = remaining
      }
    }, 1000) as unknown as number // 类型转换，适配uni-app
  }

  onLoad((options: any) => {
    status.value = options.status
    deviceId.value = options.deviceId
    pointName.value = options.pointName
  })

  // 处理输入框点击事件
  const handleInputClick = (type: string) => {
    nextTick(() => {
      activeInput.value = type
    })
  }

  // 处理聚焦事件（阻止输入法弹出）
  const handleInputFocus = (type: string, e?: any) => {}

  // 数字键盘输入
  function onKeyPress(val: any) {
    if (!activeInput.value) return
    if (activeInput.value === 'phone' && phone.value.length < 11) {
      phone.value += val
    } else if (activeInput.value === 'password' && password.value.length < 4) {
      password.value += val
    }
  }

  // 删除输入
  function onDelete() {
    if (!activeInput.value) return
    if (activeInput.value === 'phone') {
      phone.value = phone.value.slice(0, -1)
    } else if (activeInput.value === 'password') {
      password.value = password.value.slice(0, -1)
    }
  }

  async function onOpen() {
    if (!phone.value || !password.value) {
      return uni.showToast({ title: '请填手机号和密码', icon: 'none', duration: 2000 })
    }
    if (phone.value.length !== 11) {
      return uni.showToast({ title: '请输入11位手机号', icon: 'none', duration: 2000 })
    }
    const result = await ordergetUserStoragePbEnd(deviceId.value, phone.value, password.value)
    if (result) {
      detail.value = result.data
      isShow.value = true
    }
  }

  const openSubmit = async (statusStr: string) => {
    try {
      uni.showLoading({ title: '验证中...', mask: true })
      const result = await orderPbEnd(deviceId.value, phone.value, password.value, statusStr)
      if (result) {
        uni.showToast({ title: '开门成功', icon: 'success' })
        if (countdownTimer.value) {
          clearInterval(countdownTimer.value)
          countdownTimer.value = null
        }
        uni.redirectTo({ url: `/pages/index/success?pointName=${pointName.value}` })
      }
    } catch (error) {
      uni.showToast({ title: '操作失败', icon: 'none', duration: 2000 })
      initCountdown()
    } finally {
      uni.hideLoading()
    }
  }

  onMounted(() => initCountdown())

  // 组件卸载时强制清除定时器
  onUnmounted(() => {
    if (countdownTimer.value) {
      clearInterval(countdownTimer.value)
      countdownTimer.value = null
    }
  })

  const onClick = () => {
    uni.navigateBack()
  }
</script>

<style scoped lang="scss">
  .flex_header_main {
    position: relative;
  }
  .close {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
  }

  .img_setp {
    gap: 52rpx;
    img {
      width: 100%;
      border-radius: 16rpx;
      object-fit: cover;
      vertical-align: bottom;
    }
  }
  .return_home {
    font-size: 48rpx;
    color: #076bf2;
    margin-top: 48rpx;
    img {
      width: 64rpx;
      height: 64rpx;
      vertical-align: bottom;
      margin-right: 20rpx;
    }
  }
  .flex_1 {
    flex: 1;
  }
  .baoguo_main {
  }
  .baoguo_main_content {
    display: flex;
    background: #ffffff;
    box-shadow: 0px 8rpx 68rpx 0px rgba(0, 0, 0, 0.08);
    padding: 100rpx 58rpx;
    gap: 102rpx;
    margin: 48rpx 0;
    width: 100%;
  }
  .step-bar {
    display: flex;
    align-items: center;
    padding: 30rpx 60rpx;
    background-color: transparent;
    position: relative;
  }

  .step-track {
    position: absolute;
    top: 68rpx;
    left: 0;
    right: 0;
    height: 6rpx;
    background-color: rgba(255, 255, 255, 0.3);
    transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    z-index: 1;
  }

  .step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 1;
    position: relative;
  }

  .step-icon-wrapper {
    width: 76rpx;
    height: 76rpx;
    border-radius: 50%;
    -webkit-border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 16rpx;
    transition: all 0.3s ease;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }

  .step-icon-wrapper.active {
    background-color: #ffffff;
    color: #2196f3;
    box-shadow: 0 0 0 12rpx rgba(255, 255, 255, 0.25);
    -webkit-box-shadow: 0 0 0 12rpx rgba(255, 255, 255, 0.25);
  }

  .step-icon {
    font-size: 36rpx;
  }

  .step-text {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
    transition: all 0.3s ease;
    font-weight: 500;
  }

  .step-text.active {
    color: #ffffff;
    text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
  }

  .content-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 36rpx;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  .main-content {
    width: 100%;
    display: flex;
    gap: 36rpx;
    height: 100%;
  }

  .section_content {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-content: space-between;
  }

  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 80rpx;
    padding: 0 10rpx;
    transition: transform 0.2s ease;
  }

  .form-item:active {
    transform: translateX(4rpx);
  }
  .title {
    font-weight: normal;
    font-size: 72rpx;
    color: #333333;
    font-weight: 700;
  }

  .label-wrapper {
    display: flex;
    align-items: center;
    width: 240rpx;
    font-size: 52rpx;
  }

  .input-box {
    flex: 1;
    font-size: 56rpx;
    color: #2d3748;
    cursor: pointer;
    height: 164rpx;
    line-height: 164rpx;
    background: #f7f7f7;
  }

  .input-box.focused {
  }

  :deep(.uni-easyinput__content-input) {
    height: 164rpx !important;
    line-height: 164rpx !important;
    font-size: 56rpx !important;
    background: #f7f7f7 !important;
  }

  :deep(.uni-easyinput__input[readonly]) {
    color: #000000 !important;
    opacity: 1 !important;
    -webkit-text-fill-color: #000000 !important;
  }
  :deep(.uni-input-input) {
    color: #000000 !important;
    pointer-events: none;
    opacity: 1 !important;
    -webkit-text-fill-color: #000000 !important;
  }

  :deep(.uni-easyinput__content) {
    padding: 0 !important;
    border: none !important;
    background-color: transparent !important;
  }
  :deep(.uni-input-placeholder) {
    color: #999999 !important;
    font-size: 56rpx !important;
  }

  .keyboard {
    display: flex;
    flex-direction: column;
    gap: 40rpx;
    justify-content: center;
  }

  .keyboard-row {
    display: flex;
    flex: 1;
    justify-content: space-around;
    gap: 60rpx;
  }

  .key {
    width: 94px;
    height: 54px;
    background: #f7f7f7;
    border-radius: 16rpx;
    font-size: 56rpx;
    color: #333333;
  }

  .key-delete {
    background: #fddfe1;
    color: #ff1127;
  }

  .footer {
    padding: 36rpx;
    background-color: #fff;
    box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
    -webkit-box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
  }

  .open-btn {
    background: linear-gradient(270deg, #58b5ec 0%, #0065f2 100%);
    border-radius: 28rpx;
    padding: 20rpx;
    color: #ffffff;
    font-size: 84rpx;
    color: #ffffff;
    text-align: center;
  }

  .open-btn.disabled {
    background: linear-gradient(90deg, #b3d9ff 0%, #90caf9 100%);
    opacity: 0.8;
    box-shadow: none;
  }

  .open-btn:not(.disabled):active {
    background: linear-gradient(90deg, #1976d2 0%, #3949ab 100%);
    transform: scale(0.99);
    box-shadow: 0 2rpx 10rpx rgba(33, 150, 243, 0.3);
  }

  .btn-icon {
    transform: translateY(2rpx);
  }

  :deep(.uni-easyinput__input:disabled) {
    color: #2d3748 !important;
    opacity: 1 !important;
    -webkit-text-fill-color: #2d3748 !important;
    background-color: transparent !important;
    cursor: pointer !important;
  }

  :deep(.uni-easyinput[disabled]) {
    opacity: 1 !important;
  }

  .input-box:active {
    background-color: #f0f7ff;
  }

  .zzc_main {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999;
  }
  .tip_dialog {
    width: 1300rpx;
    border-radius: 32rpx;
    position: relative;
    background: #ffffff;
    padding: 80rpx;
    .title {
      color: #f55535;
      font-weight: 500;
      font-size: 120rpx;
    }
    .tip_text {
      font-size: 58rpx;
      color: #333333;
      margin: 32rpx 0;
    }
    .btn {
      font-size: 70rpx;
      background: linear-gradient(270deg, #f99f55 0%, #f55535 100%);
      border-radius: 28rpx;
      text-align: center;
      border-radius: 22rpx;
      color: #ffffff;
      padding: 30rpx 0 20rpx 0;
      .btn_text {
        font-size: 40rpx;
      }
    }
  }
  .img_row {
    img {
      width: 140rpx;
      height: 140rpx;
      border-radius: 16rpx;
    }
  }

  .img_setp {
    gap: 52rpx;
  }
  .img_row_right {
    img {
      height: 20px;
    }
  }
</style>
